function [ data ] = RecoverData( bits )
%RECOVERDATA Recovers data from received bits
%   As per 1443-3



% We should have a multiple of (8 + p) bits
length = size(bits,2);

complete = floor(length / 9);

disp([num2str(complete) '/' num2str(ceil(length/9)) ' bytes of data received in ' num2str(length) ' bits (' num2str((complete + 1) * 9 - length) ' missing).']);

% just treat as UID
for i = 1:1:complete
    dix = complete+2-i;
    bytestart = length - i * 9 + 1;
    byteend = length - (i - 1) * 9 -1;
    byte = bits(bytestart:byteend);
    data(dix,:) = fliplr(byte);
    pbit = bits(byteend + 1);
    correct(i) = CheckParity(data(dix,:),pbit);
end

if sum(correct) ~= complete
    disp('A parity check failed');
    return;
else
    disp('All parities are correct');
end

% r1 = r2 ^ r3 ^ r4 ^ r5
data(1,:) = xor(xor(xor(data(end,:), data(end-1,:)),data(end-2,:)),data(end-3,:));

% TODO: add case for receiving of all bytes so upon parity errors other
% bytes can be restored. Handle parity errors

end

function [ bool ] = CheckParity ( block, parity ) 
%RECOVERDATA Recovers data from received bits
% Checks parity by examining odd number of 1's in block

if mod(sum([block parity]),2) == 1
    bool = true;
else
    bool = false;
end
end